package com.hubiao.basics.pattern.proxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Description
 *
 * @author hubiao
 * @since 2021-01-25 23:00
 */
public class DynamicProxy implements MethodInterceptor {

    private Object target;

    public DynamicProxy(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        //1.工具类
        Enhancer enhancer = new Enhancer();
        //2.设置父类
        enhancer.setSuperclass( target.getClass() );
        //3.设置回调函数
        enhancer.setCallback( this );
        //4.创建子类(代理对象)
        Object object = enhancer.create();
        return object;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        //模拟事务
        System.out.println( "事务开始了" );
        method.invoke( target, objects );
        System.out.println( "事务结束了" );
        return null;
    }
}
